package yunjiao.javatutorials.apache.kafka.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yunjiao.javatutorials.apache.kafka.component.KafkaMessageProducer;
import yunjiao.javatutorials.apache.kafka.model.Order;
import yunjiao.javatutorials.apache.kafka.model.OrderCreatedEvent;

import java.util.UUID;

/**
 * 订单服务
 *
 * @author yangyunjiao
 */
@Service
@Slf4j
public class OrderService {

    private final KafkaMessageProducer kafkaMessageProducer;

    public OrderService(KafkaMessageProducer kafkaMessageProducer) {
        this.kafkaMessageProducer = kafkaMessageProducer;
    }

    @Transactional
    public Order createOrder(Order request) {
        // 1. 创建订单（数据库操作）
        Order order = saveOrder(request);

        // 2. 发送订单创建事件
        OrderCreatedEvent event = convertToEvent(order);
        kafkaMessageProducer.sendOrderCreatedEvent(event);

        log.info("Order created and event published: orderId={}", order.getOrderId());
        return order;
    }

    private Order saveOrder(Order request) {
        request.setOrderId(UUID.randomUUID().toString());
        // 实际应该保存到数据库
        return request;
    }

    private OrderCreatedEvent convertToEvent(Order order) {
        OrderCreatedEvent event = new OrderCreatedEvent();
        event.setOrderId(order.getOrderId());
        event.setUserId(order.getUserId());
        event.setAmount(order.getAmount());
        event.setItems(order.getItems());

        return event;
    }
}
